<template>
    <div v-if="showType == 'card'" style="margin-top: 16px">
        <el-row :gutter="20" v-loading="loading">
            <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" v-for="(item, index) in deviceList" :key="index" class="device-item">
                <el-card :body-style="{ padding: '0px' }" shadow="always" class="card-item">
                    <div class="item-title">
                        <div>
                            <el-image class="img" lazy :preview-src-list="[baseUrl + item.imgUrl]" :src="baseUrl + item.imgUrl" fit="cover" v-if="item.imgUrl != null && item.imgUrl != ''"></el-image>
                            <el-image class="img" :preview-src-list="[require('@/assets/images/gateway.png')]" :src="require('@/assets/images/gateway.png')" fit="cover" v-else-if="item.deviceType == 2"></el-image>
                            <el-image class="img" :preview-src-list="[require('@/assets/images/video.png')]" :src="require('@/assets/images/video.png')" fit="cover" v-else-if="item.deviceType == 3"></el-image>
                            <el-image class="img" :preview-src-list="[require('@/assets/images/product.png')]" :src="require('@/assets/images/product.png')" fit="cover" v-else></el-image>
                        </div>
                        <div class="title">
                            <div class="name">{{ item.deviceName }}</div>
                        </div>
                        <div style="width: 45px"></div>
                        <div class="status">
                            <div class="icon-wrap">
                                <!-- <el-tooltip :content="$t('device.index.105953-62')" placement="top" v-if="!item.canSeeCode">
                                    <svg-icon class="item" icon-class="qrcode" v-hasPermi="['iot:device:query']" />
                                </el-tooltip> -->
                                <svg-icon class="item" style="cursor: pointer" icon-class="qrcode" @click="$emit('openSummaryDialog', item)" v-if="item.canSeeCode" v-hasPermi="['iot:device:query']" />
                                <svg-icon class="item" v-if="item.status == 3 && item.rssi >= '-55'" icon-class="wifi_4" />
                                <svg-icon class="item" v-else-if="item.status == 3 && item.rssi >= '-70' && item.rssi < '-55'" icon-class="wifi_3" />
                                <svg-icon class="item" v-else-if="item.status == 3 && item.rssi >= '-85' && item.rssi < '-70'" icon-class="wifi_2" />
                                <svg-icon class="item" v-else-if="item.status == 3 && item.rssi >= '-100' && item.rssi < '-85'" icon-class="wifi_1" />
                                <svg-icon class="item" v-else icon-class="wifi_0" />
                            </div>
                        </div>
                    </div>

                    <el-row :gutter="10">
                        <el-col :span="14" style="padding: 0px 0 0 30px; margin-bottom: -10px">
                            <el-descriptions :column="1" size="small" style="margin-top: 10px; white-space: nowrap; overflow: hidden">
                                <el-descriptions-item :label="$t('device.index.105953-20')">
                                    {{ item.serialNumber }}
                                </el-descriptions-item>
                            </el-descriptions>
                        </el-col>
                        <el-col :span="10" style="padding: 0px 30px 0 0px; margin-bottom: -10px">
                            <el-descriptions :column="1" size="small" style="margin-top: 10px; white-space: nowrap">
                                <el-descriptions-item :label="$t('device.index.105953-59')">
                                    {{ item.tenantName }}
                                </el-descriptions-item>
                            </el-descriptions>
                        </el-col>
                    </el-row>
                    <el-row :gutter="10">
                        <el-col :span="14" style="padding: 0px 0 0 30px">
                            <el-descriptions :column="1" size="small" style="margin-top: 10px; white-space: nowrap">
                                <el-descriptions-item :label="$t('device.index.105953-39')">
                                    {{ item.productName }}
                                </el-descriptions-item>
                            </el-descriptions>
                        </el-col>
                        <el-col :span="10" style="padding: 0px 30px 0 0px">
                            <el-descriptions :column="1" size="small" style="margin-top: 10px; white-space: nowrap">
                                <el-descriptions-item :label="$t('device.index.105953-32')">
                                    {{ parseTime(item.activeTime, '{y}-{m}-{d}') || $t('home.notActive') }}
                                </el-descriptions-item>
                            </el-descriptions>
                        </el-col>
                    </el-row>

                    <el-divider class="divider" />
                    <div style="height: 39px; padding: 0 10px; display: flex; align-items: center; justify-content: space-evenly">
                        <el-button
                            size="mini"
                            type="text"
                            @click="
                                HistoryData = true;
                                handleEditDevice(item);
                            "
                            v-hasPermi="['iot:device:query']"
                            style="color: #fff"
                        >
                            {{ $t('device.running-status.866086-37') }}
                        </el-button>
                        <span style="width: 1px; margin: 0px 10px; font-size: 16px; color: #486ff2" v-hasPermi="['iot:device:query']">|</span>
                        <el-button
                            size="mini"
                            type="text"
                            @click="
                                RealTimeData = true;
                                handleRunDevice(item);
                            "
                            v-hasPermi="['iot:device:query']"
                            v-if="item.deviceType !== 3"
                            style="color: #fff"
                        >
                            {{ $t('topo.components.propertyBar.index.038495-340') }}
                        </el-button>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <div>
            <el-dialog
                :title="$t('topo.components.propertyBar.index.038495-340')"
                :visible.sync="RealTimeData"
                append-to-body
                width="1200px"
                custom-class="custom-dialog-now"
                @opened="handleDialogOpened"
                v-if="RealTimeData"
            >
                <el-row :gutter="20">
                    <el-col :span="6" v-for="(gauge, index) in gaugeCharts" :key="index">
                        <div class="gauge-container" style="border: 1px solid #486ff2; border-radius: 8px; padding: 10px; margin-bottom: 20px">
                            <div :ref="'gaugeChart' + index" style="width: 100%; height: 250px"></div>
                        </div>
                    </el-col>
                </el-row>
            </el-dialog>
            <el-dialog :title="$t('device.running-status.866086-37')" :visible.sync="HistoryData" append-to-body width="1900px" custom-class="custom-dialog-history">
                <DeviceStatistic :productId="productId" :serialNumber="serialNumber" :deviceList="deviceList" />
            </el-dialog>
        </div>
    </div>
</template>

<script>
import { parseTime } from '@/utils/ruoyi';
import * as echarts from 'echarts';
import DeviceStatistic from './deviceStatistic.vue';
import { getDeviceRunningStatus } from '@/api/iot/device';

export default {
    name: 'DeviceCard',
    components: { DeviceStatistic },
    data() {
        return {
            RealTimeData: false,
            HistoryData: false,
            gaugeCharts: [],
            chartInstances: [],
            //传给deviceStatistic.vue 的参数
            productId: '',
            serialNumber: '',
        };
    },
    props: {
        deviceList: {
            type: Array,
            default: () => [],
        },
        loading: {
            type: Boolean,
            default: false,
        },
        showType: {
            type: String,
            default: 'card',
        },
        baseUrl: {
            type: String,
            default: '',
        },
    },
    watch: {
        RealTimeData(val) {
            if (val) {
                // 对话框打开时，图表初始化由handleRunDevice方法处理
                // 避免重复初始化
            } else {
                this.disposeCharts();
            }
        },
    },
    methods: {
        parseTime,
        //查询设备实时运行状态
        deviceStatus(deviceId) {
            return new Promise((resolve, reject) => {
                getDeviceRunningStatus({ deviceId: deviceId })
                    .then((response) => {
                        if (response.code === 200) {
                            // 将数据赋给仪表盘
                            this.updateGaugeChartsWithRealData(response.data);
                            resolve(response.data);
                        } else {
                            reject(new Error(response.msg || '获取设备状态失败'));
                        }
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
        handleRunDevice(row) {
            // 先查询设备数据
            this.deviceStatus(row.deviceId)
                .then(() => {
                    // 数据获取成功后打开对话框
                    this.RealTimeData = true;
                })
                .catch((error) => {
                    this.$message.error('获取设备实时数据失败: ' + error.message);
                });
        },
        handleEditDevice(row) {
            this.productId = row.productId;
            this.serialNumber = row.serialNumber;
            // console.log(row);
            // console.log(this.deviceList);
            // console.log(this.productId);
            // console.log(this.serialNumber);
        },

        // 对话框打开后初始化图表
        handleDialogOpened() {
            console.log('对话框已完全打开，开始初始化图表');
            this.initGaugeCharts();
        },

        // 对话框打开后初始化图表
        handleDialogOpened() {
            console.log('对话框已完全打开，开始初始化图表');
            this.initGaugeCharts();
        },
        initGaugeCharts() {
            this.disposeCharts();
            this.chartInstances = [];

            // 使用延迟和重试机制确保DOM完全渲染
            this.initChartsWithRetry(0);
        },

        // 带重试机制的图表初始化
        initChartsWithRetry(retryCount) {
            if (retryCount >= 3) {
                console.error('图表初始化失败，已达到最大重试次数');
                return;
            }

            this.$nextTick(() => {
                let allChartsReady = true;

                this.gaugeCharts.forEach((gauge, index) => {
                    const chartRef = this.$refs['gaugeChart' + index];

                    // 检查ref是否存在
                    if (!chartRef) {
                        console.warn(`图表容器 gaugeChart${index} 未找到，重试 ${retryCount + 1}/3`);
                        allChartsReady = false;
                        return;
                    }

                    // 获取DOM元素（ref可能是数组，取第一个）
                    const chartDom = Array.isArray(chartRef) ? chartRef[0] : chartRef;

                    // 强制设置DOM元素尺寸
                    chartDom.style.width = '260px';
                    chartDom.style.height = '260px';
                    chartDom.style.display = 'block';

                    try {
                        const chart = echarts.init(chartDom);
                        const option = {
                            tooltip: {
                                formatter: '{a} <br/>{b} : {c} ' + gauge.unit,
                                backgroundColor: '#486ff2', // 与主题色一致
                                borderColor: '#486ff2',
                                textStyle: {
                                    color: '#fff',
                                },
                            },
                            series: [
                                {
                                    name: gauge.name,
                                    type: 'gauge',
                                    min: gauge.min,
                                    max: gauge.max,
                                    progress: {
                                        show: true,
                                    },
                                    axisLine: {
                                        lineStyle: {
                                            color: [[1, '#fff']],
                                        },
                                    },
                                    axisLabel: {
                                        color: '#fff',
                                    },
                                    axisTick: {
                                        lineStyle: {
                                            color: '#fff',
                                        },
                                    },
                                    splitLine: {
                                        lineStyle: {
                                            color: '#fff',
                                        },
                                    },
                                    detail: {
                                        fontSize: 14,
                                        offsetCenter: [0, '70%'],
                                        valueAnimation: true,
                                        formatter: '{value} ' + gauge.unit,
                                        color: '#fff',
                                    },
                                    title: {
                                        offsetCenter: [0, '100%'],
                                        color: '#fff',
                                    },
                                    data: [
                                        {
                                            value: gauge.value,
                                            name: gauge.name,
                                        },
                                    ],
                                },
                            ],
                        };

                        chart.setOption(option);
                        this.chartInstances.push(chart);
                    } catch (error) {
                        console.error(`初始化图表 gauge-chart-${index} 失败:`, error);
                        allChartsReady = false;
                    }
                });

                if (!allChartsReady && this.chartInstances.length === 0) {
                    // 如果有图表未初始化成功，延迟后重试
                    setTimeout(() => {
                        this.initChartsWithRetry(retryCount + 1);
                    }, 100);
                } else {
                    // 监听窗口大小变化，重新调整图表大小
                    window.addEventListener('resize', this.handleResize);
                }
            });
        },
        // 根据真实数据更新仪表盘
        updateGaugeChartsWithRealData(deviceData) {
            if (!deviceData || !deviceData.thingsModels) return;

            // 根据接口返回的数据结构更新仪表盘数据
            const realGaugeData = [];

            // 映射设备数据到仪表盘配置
            deviceData.thingsModels.forEach((model) => {
                const gaugeConfig = this.getGaugeConfigByModelId(model.id, model);
                if (gaugeConfig) {
                    realGaugeData.push(gaugeConfig);
                }
            });

            // 更新仪表盘数据
            this.gaugeCharts = realGaugeData.length > 0 ? realGaugeData : this.gaugeCharts;

            // 如果对话框已经打开，重新初始化图表
            if (this.RealTimeData) {
                this.$nextTick(() => {
                    this.initGaugeCharts();
                });
            }
        },

        // 根据模型ID获取对应的仪表盘配置
        getGaugeConfigByModelId(modelId, modelData) {
            // 如果提供了模型数据，使用接口返回的数据范围
            if (modelData && modelData.datatype) {
                return {
                    name: modelData.name,
                    min: parseFloat(modelData.datatype.min) || 0,
                    max: parseFloat(modelData.datatype.max) || 100,
                    unit: modelData.datatype.unit || '',
                    value: parseFloat(modelData.value) || 0,
                };
            }

            return gaugeConfigs[modelId];
        },
        disposeCharts() {
            this.chartInstances.forEach((chart) => {
                if (chart) {
                    chart.dispose();
                }
            });
            this.chartInstances = [];
        },
        handleResize() {
            this.chartInstances.forEach((chart) => {
                if (chart) {
                    chart.resize();
                }
            });
        },
    },
    beforeDestroy() {
        this.disposeCharts();
        window.removeEventListener('resize', this.handleResize);
    },
};
</script>

<style lang="scss" scoped>
.device-item {
    margin-bottom: 20px;
    text-align: center;

    .card-item {
        .item-title {
            display: -webkit-box;
            flex-direction: row;
            align-items: center;
            position: relative;
            padding: 18px;

            .img {
                height: 58px;
                width: 58px;
                border-radius: 10px;
            }

            .title {
                flex: 1;
                text-align: left;
                margin-left: 16px;

                .name {
                    font-weight: 500;
                    font-size: 16px;
                    color: #fff;
                    line-height: 22px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .tag-wrap {
                    margin-top: 10px;
                    display: flex;
                    flex-direction: row;
                }
            }

            .status {
                position: absolute;
                right: -1px;
                top: 24px;

                .icon-wrap {
                    display: flex;
                    flex-direction: row;
                    align-items: center;
                    padding: 0 8px;

                    .item {
                        width: 22px;
                        height: 22px;
                        margin: 0 5px;
                        color: #909399;
                    }
                }
            }
        }
    }
}

::v-deep .el-descriptions .el-descriptions__body {
    background-color: transparent !important;
}

::v-deep .el-descriptions .el-descriptions__table {
    background-color: transparent !important;
}

::v-deep .el-descriptions .el-descriptions__table tbody tr {
    color: #fff;
    background-color: transparent !important;
}

::v-deep .el-descriptions .el-descriptions__table tbody tr td {
    background-color: transparent !important;
    border: none !important;
}
.divider {
    margin: 20px 0 0;
    height: 1px;
    background-color: #486ff2;
}
.el-card {
    margin-bottom: 15px;
    padding-top: 10px;
    padding-left: 15px;
    padding-right: 15px;
    color: #fff;
    border-radius: 8px;
    border-width: #{px2vw(1)};
    border-style: solid;
    border-color: #486ff2;
    background-color: rgba(0, 11, 61, 0.79);
}
::v-deep .el-dialog {
    background-color: rgba(0, 11, 61, 0.9);
}
::v-deep .el-dialog__title {
    color: #fff !important;
}
::v-deep .custom-dialog-now {
    margin-top: 90px !important;
}
</style>
